package leecode.DFS;

import java.util.Random;

/**
 * public 参数1 DFS（参数2）{
 * if（返回条件成立）{
 * return 参数；
 * }
 * DFS（下一步）；
 * }
 */

public class Solution {
    public int numIsLands(char[][] grid) {
        int res = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                // 找到第一个
                if (grid[i][j] == '1') {
                    res++;
                    dfs(i, j, grid);
                }
            }
        }
        return res;
    }

    private void dfs(int i, int j, char[][] grid) {
        if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] != '1') {
            return;
        }
        grid[i][j] = '0';
        dfs(i + 1, j, grid);
        dfs(i - 1, j, grid);
        dfs(i, j + 1, grid);
        dfs(i, j - 1, grid);
    }

    public int numIsLandsSelf(char[][] grid) {
        int res = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    res++;
                    startDfs(i, j, grid);
                }
            }
        }
        Random random = new Random();
        for (int i = 0; i < 50; i++) {
            for (int j = 0; j < 50; j++) {
                int i1 = random.nextInt(2);
                System.out.print(i1 == 1 ? "*" : 'O');
            }
            System.out.println();
        }
        return res;
    }

    private void startDfs(int i, int j, char[][] grid) {
        if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] == '0') {
            return;
        }
        grid[i][j] = '0';
        startDfs(i + 1, j, grid);
        startDfs(i, j + 1, grid);
        startDfs(i - 1, j, grid);
        startDfs(i, j - 1, grid);
    }
}


